package com.htudata.transctAlarm.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.time.Clock;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.htudata.alarm.pojo.po.AlarmLevelPO;
import com.htudata.core.util.operation.CollectionsOperationUtils;
import com.htudata.core.util.operation.DateTimeOperationUtils;
import com.htudata.core.util.operation.MathOperationUtils;
import com.htudata.core.util.operation.StringOperationUtils;
import com.htudata.transctAlarm.dao.TransctAlarmDao;
import com.htudata.zabbix.problem.service.ProblemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class TransctAlarmDetailHistoryService {

  @Autowired
  private ProblemService problemService;
  
  @Autowired
  private TransctAlarmLevelService alarmLevelService;
  
  @Autowired
  private TransctAlarmDao alarmDao;
  
  @Value("${show_default_value}")
  private String show_default_value;
  
  @Value("${item_value_decimal}")
  private int item_value_decimal;
  
  public List<Object> getAlarmHistoryList(String triggerId, int type, long days) throws Exception  {
    LocalDateTime endTime = LocalDateTime.now(Clock.system(ZoneId.of("Asia/Shanghai")));
    LocalDateTime startTime = endTime.minusDays(days);
    if (type == 0) {
      long endTimeSecond = endTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000L;
      long startTimeSecond = startTime.toInstant(ZoneOffset.of("+8")).toEpochMilli() / 1000L;
      JSONArray problems = this.alarmDao.selectZabbixProblemsByTriggerId(
          Long.parseLong(triggerId), startTimeSecond, endTimeSecond);
      if (!CollectionsOperationUtils.isValidCollection((Collection)problems))
        return Collections.EMPTY_LIST; 
      return problemsToAlarmHistory(problems);
    } 
    DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    long endTimeInt = Long.parseLong(df.format(endTime));
    long startTimeInt = Long.parseLong(df.format(startTime));
    return getLocalAlarmHistory(Long.parseLong(triggerId), startTimeInt, endTimeInt);
  }
  
  public List<Object> getLocalAlarmHistory(long triggerId, long startTime, long endTime) throws Exception {
    List<Object> AlarmHistoryList = new ArrayList();
    JSONArray localProblems = this.alarmDao.selectAlarmHistoryByTriggerId(triggerId, startTime, endTime);
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(null);
    localProblems.forEach(localProblem -> {
        try {
          JSONObject  localProblemJson = localProblemToAlarm((JSONObject)localProblem, alarmLevelList);
          AlarmHistoryList.add(localProblemJson);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        });
    return AlarmHistoryList;
  }
  
  private List<Object> problemsToAlarmHistory(JSONArray problems) {
    List<Object> AlarmHistoryList = new ArrayList();
    List<AlarmLevelPO> alarmLevelList = this.alarmLevelService.getAlarmLevelList(null);
    problems.forEach(problem -> {
          JSONObject problemJson = zabbixProblemToAlarm2((JSONObject)problem, alarmLevelList);
          AlarmHistoryList.add(problemJson);
        });
    return AlarmHistoryList;
  }
  
  private JSONObject zabbixProblemToAlarm(JSONObject problem, List<AlarmLevelPO> alarmLevelList) {
    JSONObject result = new JSONObject();
    result.put("alarmId", Long.valueOf(problem.getLongValue("eventid")));
    result.put("triggerId", Long.valueOf(problem.getLongValue("objectid")));
    result.put("problem", problem.getString("name"));
    result.put("ack", (problem.getIntValue("acknowledged") == 1) ? "已确认" : "未确认");
    result.put("alarmTime", DateTimeOperationUtils.format(LocalDateTime.ofEpochSecond(problem.getLongValue("clock"), 0, ZoneOffset.ofHours(8)), "yyyyMMdd HH:mm:ss"));
    long recoveryTimeSecond = problem.getLongValue("r_clock");
    if (recoveryTimeSecond == 0L) {
      result.put("recoveryTime", "");
      result.put("status", "问题");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, problem.getIntValue("severity"));
      result.put("color", alarmLevelPO.getColor());
      int currentTimestamp = (int)(System.currentTimeMillis() / 1000L);
      long timeStampShift = (currentTimestamp - problem.getIntValue("clock"));
      result.put("duration", DateTimeOperationUtils.timeStampToStringNew(timeStampShift, 3));
    } else {
      result.put("recoveryTime", DateTimeOperationUtils.format(LocalDateTime.ofEpochSecond(problem.getLongValue("clock"), 0, ZoneOffset.ofHours(8)), "yyyyMMdd HH:mm:ss"));
      result.put("status", "已解决");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, 0);
      result.put("color", alarmLevelPO.getColor());
      long timeStampShift = recoveryTimeSecond - problem.getLongValue("clock");
      result.put("duration", DateTimeOperationUtils.timeStampToStringNew(timeStampShift, 3));
    } 
    return result;
  }
  
  private JSONObject zabbixProblemToAlarm2(JSONObject problem, List<AlarmLevelPO> alarmLevelList) {
    JSONObject result = new JSONObject();
    result.put("alarmId", Long.valueOf(problem.getLongValue("eventid")));
    result.put("triggerId", Long.valueOf(problem.getLongValue("objectid")));
    result.put("problem", problem.getString("name"));
    result.put("ack", (problem.getIntValue("acknowledged") == 1) ? "已确认" : "未确认");
    result.put("alarmTime", DateTimeOperationUtils.format(LocalDateTime.ofEpochSecond(problem.getLongValue("clock"), 0, ZoneOffset.ofHours(8)), "yyyyMMdd HH:mm:ss"));
    result.put("value", problem.getOrDefault("value", this.show_default_value));
    if (StringOperationUtils.isValidStr2(result.getString("value"))) {
      result.put("units", problem.getString("units"));
    } else {
      result.put("units", "");
    } 
    long recoveryTimeSecond = problem.getLongValue("r_clock");
    if (recoveryTimeSecond == 0L) {
      result.put("recoveryTime", "");
      result.put("status", "问题");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, problem.getIntValue("severity"));
      result.put("color", alarmLevelPO.getColor());
      int currentTimestamp = (int)(System.currentTimeMillis() / 1000L);
      long timeStampShift = (currentTimestamp - problem.getIntValue("clock"));
      result.put("duration", DateTimeOperationUtils.timeStampToString(timeStampShift, 3));
    } else {
      result.put("recoveryTime", DateTimeOperationUtils.format(LocalDateTime.ofEpochSecond(problem.getLongValue("clock"), 0, ZoneOffset.ofHours(8)), "yyyyMMdd HH:mm:ss"));
      result.put("status", "已解决");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, 0);
      result.put("color", alarmLevelPO.getColor());
      long timeStampShift = recoveryTimeSecond - problem.getLongValue("clock");
      result.put("duration", DateTimeOperationUtils.timeStampToString(timeStampShift, 3));
    } 
    return result;
  }
  
  private JSONObject localProblemToAlarm(JSONObject problem, List<AlarmLevelPO> alarmLevelList) throws Exception {
    JSONObject result = new JSONObject();
    result.put("alarmId", Long.valueOf(problem.getLongValue("alarm_id")));
    result.put("triggerId", Long.valueOf(problem.getLongValue("trigger_id")));
    result.put("problem", problem.getString("name"));
    result.put("ack", (problem.getIntValue("status") == 1) ? "已确认" : "未确认");
    Date startTime = DateTimeOperationUtils.parse(String.valueOf(problem.getLongValue("start_time")), "yyyyMMddHHmmss");
    result.put("alarmTime", DateTimeOperationUtils.format(startTime, "yyyyMMdd HH:mm:ss"));
    String value = MathOperationUtils.round(problem.getOrDefault("value", "").toString(), this.item_value_decimal);
    value = StringOperationUtils.rvZeroAndDot(value);
    result.put("value", value);
    result.put("units", problem.getString("units"));
    long recoveryTimeSecond = problem.getLongValue("recover_time");
    if (recoveryTimeSecond == 0L) {
      result.put("recoveryTime", "");
      result.put("status", "问题");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, problem.getIntValue("level"));
      result.put("color", alarmLevelPO.getColor());
      int currentTimestamp = (int)(System.currentTimeMillis() / 1000L);
      long timeStampShift = currentTimestamp - startTime.getTime() / 1000L;
      result.put("duration", DateTimeOperationUtils.timeStampToStringNew(timeStampShift, 3));
    } else {
      Date recoveryTime = DateTimeOperationUtils.parse(String.valueOf(recoveryTimeSecond), "yyyyMMddHHmmss");
      result.put("recoveryTime", DateTimeOperationUtils.format(LocalDateTime.ofEpochSecond(recoveryTime.getTime() / 1000L, 0, ZoneOffset.ofHours(8)), "yyyyMMdd HH:mm:ss"));
      result.put("status", "已解决");
      AlarmLevelPO alarmLevelPO = TransctAlarmLevelService.getAlarmLevelInfo(alarmLevelList, 0);
      result.put("color", alarmLevelPO.getColor());
      long timeStampShift = recoveryTime.getTime() / 1000L - startTime.getTime() / 1000L;
      result.put("duration", DateTimeOperationUtils.timeStampToStringNew(timeStampShift, 3));
    } 
    return result;
  }

}
